<?php

namespace app\data\command;

use app\data\model\DataUser;
use app\data\model\DataUserDistribution;
use think\admin\Command;
use think\console\Input;
use think\console\Output;
use think\Model;
/**
 * 自动更新审核状态
 * Class UserAgent
 * @package app\data\command
 */
class UserAgentapply extends Command
{
    protected function configure()
    {
        $this->setName('xdata:UserAgentapply');
        $this->setDescription('自动审核分销申请');
    }

    /**
     * @param Input $input
     * @param Output $output
     * @return void
     * @throws \think\admin\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    protected function execute(Input $input, Output $output)
    {
        try {
            $map = [['status', '=', 0],];
            $map[] = ['apply_time', '<', date('Y-m-d H:i:s', strtotime('-2 days'))];
            [$count, $total] = [0, ($result = DataUserDistribution::mk()->where($map)->select())->count()];
            $result->map(function (Model $item) use ($total, &$count) {
                $userinfo = DataUser::mk()->where(array('id'=>$item['uuid']))->field('username')->find();
                if(empty($userinfo)) $userinfo['username'] = '';
                $this->queue->message($total, ++$count, "开始自动审核分销员申请 {$userinfo['username']}");
                $res = $item->save(['status' => 1, 'audit_remark'=>'自动审核通过','audit_time'=>\Tools::getDateTimeByTime()]);
                //更新用户分销员身份
                $userres = DataUser::mk()->where(['id'=>$item['uuid']])->save(array(
                    'is_distribution'   => 1,
                    'distribution_time' => \Tools::getDateTimeByTime(),
                    'distribution_code' => \Common::uniqidDate(16,'D'.$item['uuid'])
                ));
                sysoplog('自动审核分销员申请','系统：自动审核分销员申请：'.$userinfo['username']);

                $this->queue->message($total, $count, "完成自动审核分销员申请 {$userinfo['username']}", 1);
            });
        } catch (\Exception $exception) {
            $this->queue->error($exception->getMessage());
        }
    }
}
